//
//  LPRotatoView.swift
//  TLenPoint
//
//  Created by Docker on 2018/3/22.
//  Copyright © 2018年 Docker. All rights reserved.
//

import UIKit
import SDWebImage
let sectionNumber = 3
class LPRotatoView: UIView {

    var dataArray : [RotatoModel]?
    {
        didSet{
            if (dataArray?.count == 0){
                return
            }
            collectionView.reloadData()
            DispatchQueue.main.async {  //通知ui刷新
                let index = NSIndexPath(item: 0, section: 1);
                self.collectionView .scrollToItem(at: index as IndexPath, at: .centeredHorizontally, animated: false)
            }
        }
    }
    
    var timer:Timer!
    
    override init(frame: CGRect) {
         super.init(frame: frame)
         creatUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: -- 懒加载控件
    fileprivate lazy var collectionView :UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let collection = UICollectionView(frame: self.bounds, collectionViewLayout: layout);
        collection.delegate = self
        collection.dataSource = self
        layout.itemSize = CGSize(width: UIScreen.main.bounds.size.width, height: 200)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        collection.isPagingEnabled = true
        collection.register(LPRotatoCollectionViewCell.self, forCellWithReuseIdentifier: LPRotatoViewCELLIdetifer)

        return collection
    }()
    // MARK : UI
   
  private  func creatUI(){
   
    print(self.frame)
    self.layoutIfNeeded()
    print(self.frame)
    self.addSubview(collectionView)
    collectionView.snp.makeConstraints { (make) in
        make.edges.equalTo(self)
    }
       self.addTimer()
    }
    
     //添加
    private func addTimer(){
        timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(automation), userInfo: nil, repeats: true)
    }
    //移除
    private func removeTimer(){
        timer.invalidate()
        timer = nil
    }
    
    @objc func automation(){
        if((dataArray?.count) ?? 0 < 2){
            return
        }
        //获取当前可是cell的下标
        let indexPath = self.collectionView.indexPathsForVisibleItems.last
       
        var nextItem = (indexPath?.row)! + 1
        var nextSection = indexPath?.section
        if(nextItem == dataArray?.count){
            nextItem = 0
            nextSection = nextSection! + 1
        }
        if(nextSection == 3){
            nextSection = 1
            let index = NSIndexPath(item: nextItem, section: nextSection!)
            self.collectionView.scrollToItem(at: index as IndexPath, at: .centeredHorizontally, animated: false)
        }else{
            let index = NSIndexPath(item: nextItem, section: nextSection!)
            self.collectionView.scrollToItem(at: index as IndexPath, at: .centeredHorizontally, animated: true)
        }
        
    }
}
// MARK: -- 数据源和代理
 extension LPRotatoView:UICollectionViewDelegate,UICollectionViewDataSource
 {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return sectionNumber
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return (dataArray?.count)!*10000
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView .dequeueReusableCell(withReuseIdentifier: LPRotatoViewCELLIdetifer, for: indexPath) as! LPRotatoCollectionViewCell
        let model = dataArray![indexPath.row%(dataArray?.count)!]
        cell.imageView.sd_setImage(with: URL(string: model.imageUrl!), placeholderImage: UIImage(named: "avatar_default_big"))
        return cell
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
    }
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        self.addTimer()
    }
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.removeTimer()
    }
 }

